﻿@page "/Wms/OtherInWarehouse/Create"
@using nERP.ViewModel.Wms.OtherInWarehouseVMs
@using nERP.Model.Wms
@using System.ComponentModel.DataAnnotations
@inherits BasePage

<div>
    <ValidateForm @ref="vform" Model="@Model" OnValidSubmit="@Submit">
        <Row ItemsPerRow="ItemsPerRow.Three" RowType="RowType.Normal">
            <BootstrapInputGroupLabel @bind-Value="@Model.Entity.OtherInWarehouseCode" />
            <BootstrapInputGroup>
                <BootstrapInput @bind-Value="@Model.Entity.OtherInWarehouseCode"></BootstrapInput>
                <Button @ref="@btnSN" Icon="fas fa-plus" Text="@WtmBlazor.Localizer["Page.生成号码"]" OnClick="OnCreateSNAsync"></Button>
            </BootstrapInputGroup>
            <Select @bind-Value="@Model.Entity.OtherInTypeId" Items="AllOtherInTypes" PlaceHolder="@WtmBlazor.Localizer["Sys.PleaseSelect"]" />
            <Select @bind-Value="@Model.Entity.MakeUserId" Items="AllMakeUsers" PlaceHolder="@WtmBlazor.Localizer["Sys.PleaseSelect"]" IsPopover ShowSearch />
            <DateTimePicker @bind-Value="@Model.Entity.InvoicesDate" />
            <BootstrapInput @bind-Value="@Model.Entity.Remark" />
            <WTUploadImage @bind-Value="@Model.Entity.InvoicesImage" />
        </Row>
        <Divider Icon="fa-fw fa-solid fa-bookmark" Text="@WtmBlazor.Localizer["_Model._OtherInWarehouse._OtherInWarehouseDetail_OtherInWarehouse"]" Alignment="Alignment.Left" />


        <Table TItem="OtherInWarehouseDetail" @bind-Items="@OtherInWarehouseDetailOtherInWarehouseList" OnDeleteAsync="@OnDeleteAsync" ShowFooter="true" ShowAddButton="false"
               ShowSkeleton="true" IsStriped="true" IsBordered="true" ShowRefresh="false" ShowToolbar="true" ShowExtendButtons="true" IsExcel="true">
            <TableColumns>
                <TableColumn @bind-Field="@context.Seq" Text="@WtmBlazor.Localizer["Page.序号"]" Readonly="true" />
                <TableColumn @bind-Field="@context.OtherInWarehouseDetailCode" Text="@WtmBlazor.Localizer["Page.入库明细单号"]" Visible="false" />
                <TableColumn @bind-Field="@context.GoodsId" Text="@WtmBlazor.Localizer["Page.商品编号"]" Readonly="true" />
                <TableColumn @bind-Field="@context.GoodsName" Text="@WtmBlazor.Localizer["Page.商品名称"]" Readonly="true" />
                <TableColumn @bind-Field="@context.GoodsSpec" Text="@WtmBlazor.Localizer["Page.商品规格"]" Readonly="true" />
                <TableColumn @bind-Field="@context.GoodsUnit" Text="@WtmBlazor.Localizer["Page.计量单位"]" Readonly="true" />
                <TableColumn @bind-Field="@context.WarehouseId" Text="@WtmBlazor.Localizer["Page.仓库"]">
                    <Template Context="Value">
                        <Select Items="detailAllWarehouses" @bind-Value="Value.Row.WarehouseId" ShowLabel="false" IsDisabled="true" />
                    </Template>
                    <EditTemplate Context="Value">
                        <Select Items="detailAllWarehouses" @bind-Value="Value.WarehouseId" ShowLabel="false" IsPopover />
                    </EditTemplate>
                </TableColumn>
                <TableColumn @bind-Field="@context.OtherInNumber" Text="@WtmBlazor.Localizer["Page.入库数量"]">
                    <EditTemplate Context="V">
                        <BootstrapInput @bind-Value="V.OtherInNumber" @onfocusout="()=>Input_OnFocusout(V)" />
                    </EditTemplate>
                </TableColumn>
                <TableColumn @bind-Field="@context.Remark" Text="@WtmBlazor.Localizer["_Admin.Remark"]" />
            </TableColumns>

            <TableToolbarTemplate>
                <TableToolbarButton TItem="OtherInWarehouseDetail" Color="Color.Primary" Icon="fa-fw fa-solid fa-pen-to-square" Text="@WtmBlazor.Localizer["Sys.Select"]" OnClickCallback="@ShowDialog" />
                <Modal @ref="GoodsModal">
                    <ModalDialog Title="选择商品" IsCentered IsDraggable="true">
                        <BodyTemplate>
                            <Table TItem="nERP.ViewModel.Bas.GoodsVMs.Goods_View" @ref="GoodsTable" IsStriped="true" @bind-SelectedRows="@SelectedRows"
                                   ShowToolbar="true" ShowDefaultButtons="false" IsMultipleSelect="true" ClickToSelect="true" OnQueryAsync="GoodsListVMOnSearchGoods"
                                   AllowResizing="true" IsPagination="true" AllowDragColumn="true" ShowColumnList="true" ShowSearch="true" SearchTooltip=""
                                   OnResetSearchAsync="OnResetSearchAsync" SearchMode="SearchMode.Top" CollapsedTopSearch="true" ShowSearchText="false">
                                <SearchTemplate>
                                    <ValidateForm Model="@Model2">
                                        <Row ItemsPerRow="ItemsPerRow.Three" RowType="RowType.Inline">
                                            <BootstrapInput @bind-Value="@Model2.Searcher.GoodsCode" />
                                            <BootstrapInput @bind-Value="@Model2.Searcher.GoodsName" />
                                            <Select @bind-Value="@Model2.Searcher.GoodsTypeId" Items="AllGoodsTypes" PlaceHolder="@WtmBlazor.Localizer["Sys.All"]" />
                                        </Row>
                                    </ValidateForm>
                                </SearchTemplate>
                                <TableColumns>
                                    <TableColumn @bind-Field="@context.Goods_GoodsCode" Text="@WtmBlazor.Localizer["Page.商品编号"]" />
                                    <TableColumn @bind-Field="@context.Goods_GoodsName" Text="@WtmBlazor.Localizer["Page.商品名称"]" />
                                    <TableColumn @bind-Field="@context.Goods_GoodsSpec" Text="@WtmBlazor.Localizer["Page.规格型号"]" />
                                    <TableColumn @bind-Field="@context.Goods_GoodsType" Text="@WtmBlazor.Localizer["Page.商品类别"]" />
                                    <TableColumn @bind-Field="@context.Goods_GoodsUnit" Text="@WtmBlazor.Localizer["Page.计量单位"]" />
                                    <TableColumn @bind-Field="@context.Goods_Stock" Text="@WtmBlazor.Localizer["Page.库存"]" />
                                </TableColumns>
                            </Table>
                        </BodyTemplate>
                        <FooterTemplate>
                            <Button Text="@WtmBlazor.Localizer["Sys.OK"]" Icon="fa-regular fa-square-check" OnClick="@OnConfirm" />
                        </FooterTemplate>
                    </ModalDialog>
                </Modal>
            </TableToolbarTemplate>
            <FooterTemplate>
                <tr style="background-color:gray; font-weight:600; text-align:center;">
                    <td colspan="7">合计：</td>
                    <td>@sumOtherInNumber</td>
                </tr>
            </FooterTemplate>
        </Table>

        <div class="modal-footer table-modal-footer">
            <Button ButtonType="ButtonType.Submit" IsAsync="true" Text="@WtmBlazor.Localizer["Sys.Submit"]" />
            <Button OnClick="OnClose" Text="@WtmBlazor.Localizer["Sys.Close"]" />
        </div>

    </ValidateForm>

</div>



@code {
    [Parameter]
    public string id { get; set; }
    [Parameter]
    public string[] ids { get; set; }
    private OtherInWarehouseVM Model = new OtherInWarehouseVM();
    private ValidateForm vform { get; set; }
    private string sumOtherInNumber { get; set; }
    private async Task Submit(EditContext context)
    {

        Model.Entity.OtherInWarehouseDetail_OtherInWarehouse = OtherInWarehouseDetailOtherInWarehouseList.ToList();
        Model.Entity.OtherInWarehouseDetail_OtherInWarehouse.ForEach(x => x.OtherInWarehouseDetailCode = Model.Entity.OtherInWarehouseCode + x.Seq.ToString());

        await PostsForm(vform, "/api/Wms/OtherInWarehouse/Create", (s) => "Sys.OprationSuccess");
    }
    public void OnClose()
    {
        CloseDialog();
    }

    private List<SelectedItem> AllOtherInTypes = new List<SelectedItem>();
    private List<SelectedItem> AllMakeUsers = new List<SelectedItem>();
    private IEnumerable<OtherInWarehouseDetail> OtherInWarehouseDetailOtherInWarehouseList { get; set; } = new List<OtherInWarehouseDetail>();
    private List<OtherInWarehouseDetail> Items { get; set; } = new List<OtherInWarehouseDetail>();
    private List<SelectedItem> detailAllWarehouses = new List<SelectedItem>();
    protected override async Task OnInitializedAsync()
    {


        AllOtherInTypes = await WtmBlazor.Api.CallItemsApi("/api/Wms/OtherInWarehouse/GetDicFields入库业务类别");
        AllOtherInTypes.Insert(0, new SelectedItem { Text = WtmBlazor.Localizer["Sys.PleaseSelect"], Value = "" });
        AllMakeUsers = await WtmBlazor.Api.CallItemsApi("/api/Wms/OtherInWarehouse/GetFrameworkUsers");
        AllMakeUsers.Insert(0, new SelectedItem { Text = WtmBlazor.Localizer["Sys.PleaseSelect"], Value = "" });
        detailAllWarehouses = await WtmBlazor.Api.CallItemsApi("/api/Wms/OtherInWarehouseDetail/GetWarehouses");
        detailAllWarehouses.Insert(0, new SelectedItem { Text = WtmBlazor.Localizer["Sys.PleaseSelect"], Value = "" });

        Model.Entity.InvoicesDate = DateTime.Now;
        Model.Entity.Status = nERP.Model.StatusTypeEnum.Unaudited;
        Model.Entity.MakeUserId = UserInfo.ITCode;
        await base.OnInitializedAsync();
    }

    private Button btnSN { get; set; }
    private async Task OnCreateSNAsync(MouseEventArgs e)
    {
        var SN = await GetNewSN2("其他入库", false);
        Model.Entity.OtherInWarehouseCode = SN;
        btnSN.SetDisable(true);
    }


    private Task<bool> OnDeleteAsync(IEnumerable<OtherInWarehouseDetail> items)
    {
        items.ToList().ForEach(i => Items.Remove(i));

        sums();


        return Task.FromResult(true);
    }

    [System.Diagnostics.CodeAnalysis.NotNull]
    private Modal? GoodsModal { get; set; }
    private List<nERP.ViewModel.Bas.GoodsVMs.Goods_View> SelectedRows { get; set; } = [];

    private List<SelectedItem> AllGoodsTypes = new List<SelectedItem>();

    private nERP.ViewModel.Bas.GoodsVMs.GoodsListVM Model2 = new nERP.ViewModel.Bas.GoodsVMs.GoodsListVM();

    private Task OnResetSearchAsync(nERP.ViewModel.Bas.GoodsVMs.Goods_View item)
    {
        Model2.Searcher = new nERP.ViewModel.Bas.GoodsVMs.GoodsSearcher();
        item = new nERP.ViewModel.Bas.GoodsVMs.Goods_View();
        return Task.CompletedTask;
    }
    private async Task<QueryData<nERP.ViewModel.Bas.GoodsVMs.Goods_View>> GoodsListVMOnSearchGoods(QueryPageOptions opts)
    {

        return await StartSearch<nERP.ViewModel.Bas.GoodsVMs.Goods_View>("/api/Bas/Goods/SearchGoods", Model2.Searcher, opts);
    }


    private Task ShowDialog(IEnumerable<OtherInWarehouseDetail> items) => GoodsModal.Toggle();

    [System.Diagnostics.CodeAnalysis.NotNull]
    private Table<nERP.ViewModel.Bas.GoodsVMs.Goods_View>? GoodsTable { get; set; }

    private async Task OnConfirm()
    {
        if (SelectedRows.Count > 0)
        {
            var newSR = SelectedRows.Where(x => !Items.Select(i => i.GoodsId).Contains(x.Goods_GoodsCode)).ToList();

            foreach (var r in newSR)
            {
                var cr = new OtherInWarehouseDetail()
                    {
                        ID = Guid.NewGuid(),
                        Seq = (Items.Max(s => s.Seq) ?? 0) + 1,
                        GoodsId = r.Goods_GoodsCode,
                        GoodsName = r.Goods_GoodsName,
                        GoodsSpec = r.Goods_GoodsSpec,
                        GoodsUnit = r.Goods_GoodsUnit
                    };

                Items.Insert(Items.Count, cr);
                OtherInWarehouseDetailOtherInWarehouseList = Items;
            }
        }
        StateHasChanged();

        await GoodsModal.Toggle();
    }
    private void Input_OnFocusout(OtherInWarehouseDetail V)
    {

        sums();


    }
    /// <summary>
    /// 设置合计项
    /// </summary>
    private void sums()
    {
        sumOtherInNumber = Items.Any() ? Items.Sum(x => x.OtherInNumber)?.ToString("#0.####") : "0";
    }
}
